/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import liquibase.pro.packaged.E;
import org.apache.ibatis.annotations.Param;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.PlanLogDTO;
import org.springblade.modules.admin.entity.MaintainMalfunctionLog;
import org.springblade.modules.admin.entity.MaintainPlanContent;
import org.springblade.modules.admin.entity.MaintainPlanContentExt;
import org.springblade.modules.admin.entity.MaintainSign;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.IMaintainPlanContentExtService;
import org.springblade.modules.admin.service.IMaintainPlanContentService;
import org.springblade.modules.admin.service.IMaintainSignService;
import org.springblade.modules.admin.service.MaintainMalfunctionLogService;
import org.springblade.modules.admin.mapper.MaintainMalfunctionLogMapper;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.admin.vo.WorkTrackVO;
import org.springblade.modules.admin.vo.plan.MaintainLogStatusVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 故障单操作日志记录 服务实现类
 *
 * @author BladeX
 * @since 2021-05-11
 */
@Service
public class MaintainMalfunctionLogServiceImpl extends BaseServiceImpl<MaintainMalfunctionLogMapper, MaintainMalfunctionLog> implements MaintainMalfunctionLogService {

	@Autowired
	@Lazy
	private IMaintainPlanContentService maintainPlanContentService;

	@Autowired
	@Lazy
	private IMaintainPlanContentExtService maintainPlanContentExtService;

	@Autowired
	@Lazy
	private IMaintainSignService maintainSignService;

	@Override
	public void insertWorkLog(Long planId, String typeName, Integer planStatus) {
		BladeUser user = AuthUtil.getUser();
		// 微信群机器人的情况，暂时这样处理
		if(Func.isNull(user)){
			this.insertWorkLog(planId, typeName, planStatus, null, null, "微信群机器人");
			return;
		}
		this.insertWorkLog(planId, typeName, planStatus, null, user.getUserId(), user.getNickName());
	}

	@Override
	public void insertWorkLog(Long planId, String typeName, Integer planStatus, String ext) {
		BladeUser user = AuthUtil.getUser();
		this.insertWorkLog(planId, typeName, planStatus, ext, user.getUserId(), user.getNickName());
	}

	@Override
	public void insertWorkLog(Long planId, String typeName, Integer planStatus, String ext, Long executorId, String executor) {
		MaintainMalfunctionLog maintainMalfunctionLog = new MaintainMalfunctionLog();
		maintainMalfunctionLog.setPlanId(planId);
		maintainMalfunctionLog.setTypeName(typeName);
		maintainMalfunctionLog.setPlanStatus(planStatus);
		maintainMalfunctionLog.setExecutor(executor);
		maintainMalfunctionLog.setExecutorId(executorId);
		maintainMalfunctionLog.setTenantId(AuthUtil.getTenantId());
		maintainMalfunctionLog.setExt(ext);
		this.save(maintainMalfunctionLog);
	}

	@Override
	public void insertWorkLog(Long planId, String typeName, int planStatus, String ext, String tenantId) {
		MaintainMalfunctionLog maintainMalfunctionLog = new MaintainMalfunctionLog();
		maintainMalfunctionLog.setPlanId(planId);
		maintainMalfunctionLog.setTypeName(typeName);
		maintainMalfunctionLog.setPlanStatus(planStatus);
		maintainMalfunctionLog.setTenantId(tenantId);
		maintainMalfunctionLog.setExt(ext);
		this.save(maintainMalfunctionLog);
	}

	@Override
	public WorkTrackVO selectWorkTracks(Long planId) {
		MaintainPlanContent planContent = maintainPlanContentService.getById(planId);
		if (planContent == null) {
			throw new ServiceException("未找到相关任务工单");
		}

		WorkTrackVO workTrack = new WorkTrackVO();
		List<MaintainMalfunctionLog> workLogList = this.list(Wrappers.<MaintainMalfunctionLog>lambdaQuery()
			.eq(MaintainMalfunctionLog::getPlanId, planId)
			.eq(MaintainMalfunctionLog::getIsDeleted, BladeConstant.DB_NOT_DELETED)
			.orderByAsc(BaseEntity::getCreateTime, BaseEntity::getId));
		MaintainPlanContentExt planContentExt = maintainPlanContentExtService.getOne(Wrappers.<MaintainPlanContentExt>lambdaQuery().eq(MaintainPlanContentExt::getPlanId, planId).eq(MaintainPlanContentExt::getIsDeleted, BladeConstant.DB_NOT_DELETED), false);
		if (planContentExt != null) {
			workTrack.setTakeUpTime(String.valueOf(planContentExt.getWorkMinute()));
			workTrack.setWorkDuration(String.valueOf(planContentExt.getWorkDuration()));
			if (planContentExt.getPlanBeginTime() != null && planContentExt.getPlanEndTime() != null) {
				Long second = DateUtil.between(Date.from(planContentExt.getPlanBeginTime().atZone(ZoneId.systemDefault()).toInstant()), Date.from(planContentExt.getPlanEndTime().atZone(ZoneId.systemDefault()).toInstant()), DateUnit.SECOND);
				String secondToTime = DateUtil.secondToTime(Convert.toInt(second));
				workTrack.setTakeUpTimeSecond(secondToTime);
			}
		}
		workTrack.setWorkLogs(workLogList);

		workTrack.setTaskStatus(TaskStatusEnum.getTaskStatusByType(planContent.getTypeStatus()));

		return workTrack;
	}

	@Override
	public List<MaintainLogStatusVo> logStatusList(@Param("planId") Long planId) {
		return baseMapper.logStatusList(planId);
	}

	@Override
	public String initList() {
		List<MaintainMalfunctionLog> list = baseMapper.initList();
		for (MaintainMalfunctionLog maintainMalfunctionLog : list) {
			String ext = maintainMalfunctionLog.getExt();
			if (StrUtil.isNotEmpty(ext)) {
				try {
					PlanLogDTO planLogDTO = JSON.parseObject(ext, PlanLogDTO.class);
					MaintainSign maintainSign = maintainSignService.getById(planLogDTO.getSignId());
					if (maintainSign == null) {
						if (planLogDTO.getImage().contains("tmp")) {
							planLogDTO.setImage("https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20230727/d1abcd3e1eaf7c3aa91e1f2f43ef0d93.jpg");
						}
					} else {
						if (Convert.toStr(maintainSign.getSignImage(), "").contains("tmp") && Convert.toStr(maintainSign.getSignOutImage(), "").contains("tmp")) {
							planLogDTO.setImage("https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20230727/d1abcd3e1eaf7c3aa91e1f2f43ef0d93.jpg");
							maintainSign.setSignImage(planLogDTO.getImage());
							maintainSign.setSignOutImage(planLogDTO.getImage());
						} else {
							if (Convert.toStr(maintainSign.getSignImage(), "").contains("tmp")) {
								if (StrUtil.isNotEmpty(maintainSign.getSignOutImage()) && !maintainSign.getSignOutImage().contains("tmp")) {
									planLogDTO.setImage(maintainSign.getSignOutImage());
								} else {
									planLogDTO.setImage("https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20230727/d1abcd3e1eaf7c3aa91e1f2f43ef0d93.jpg");
								}
							} else if (Convert.toStr(maintainSign.getSignOutImage(), "").contains("tmp")) {
								if (StrUtil.isNotEmpty(maintainSign.getSignImage()) && !maintainSign.getSignImage().contains("tmp")) {
									planLogDTO.setImage(maintainSign.getSignImage());
								} else {
									planLogDTO.setImage("https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20230727/d1abcd3e1eaf7c3aa91e1f2f43ef0d93.jpg");
								}
							}
						}
						maintainSignService.updateById(maintainSign);
					}
					maintainMalfunctionLog.setExt(JSON.toJSONString(planLogDTO));
					this.updateById(maintainMalfunctionLog);
				} catch (Exception e) {
					continue;
				}

			}
		}
		return null;
	}


}

